extern crate reqwest;

use reqwest::{header, Client};
use std::collections::HashMap;
use std::result::Result;
use std::string::String;

#[derive(Deserialize, Debug)]
struct Token {
    access_token: String,
    token_type: String,
    refresh_token: String,
    expires_in: u32,
    scope: String,
}

#[derive(Deserialize, Debug)]
struct Error {
    error: String,
    error_description: String,
}

fn get_token() -> Result<Token, Error> {
    let client = Client::new();
    let mut params = HashMap::new();
    params.insert("grant_type", "password");
    params.insert("scope", "write read");
    params.insert("username", "sccn.sq@gmail.com");
    params.insert("password", "ksd123");

    match client
        .post("http://app.kaoshidian.com/oauth/token")
        .header(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("application/x-www-form-urlencoded"),
        )
        .header(
            header::AUTHORIZATION,
            header::HeaderValue::from_static("Basic Y2xpZW50YXBwOjEyMzQ1Ng=="),
        )
        .form(&params)
        .send()
    {
        Ok(mut res) => {
            if res.status().is_success() {
                let token: Token = res.json().unwrap();
                Ok(token)
            } else {
                let error: Error = res.json().unwrap();
                Err(error)
            }
        }
        Err(e) => Err(Error {
            error: e.to_string(),
            error_description: e.to_string(),
        }),
    }
}

// fn get_google_code(token: &str) -> Result<String, Error> {}

fn main() {
    let token = get_token();
    println!("{:#?}", token);
}
